package com.jyw.business.obstacles.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.jyw.business.obstacles.domain.ObsOrderInfo;
import com.jyw.business.obstacles.domain.dto.web.*;
import com.jyw.business.obstacles.domain.vo.web.*;
import com.jyw.business.obstacles.service.IObsLocalPhoneService;
import com.jyw.business.obstacles.service.IObsOrderFaultService;
import com.jyw.business.obstacles.service.IObsOrderInfoService;
import com.jyw.business.obstacles.service.IObsOrderProcessService;
import com.jyw.business.obstacles.utils.WordUtil;
import com.jyw.common.constant.ConfigKeyConstant;
import com.jyw.common.core.controller.BaseController;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.core.domain.model.SimpleDto;
import com.jyw.common.core.page.BasePage;
import com.jyw.common.core.page.TableDataInfo;
import com.jyw.common.exception.ServiceException;
import com.jyw.common.utils.DownloadUtil;
import com.jyw.system.domain.vo.SimpleUserVo;
import com.jyw.system.service.ISysConfigService;
import com.jyw.system.utils.ConversionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 沈峻
 * @ClassName ObsServerController
 * @Description 服务台
 * @Date 2023/8/10 15:30
 **/
@RestController
@RequestMapping("/obstacles/server")
@Api(tags = "服务台")
public class ObsServerController extends BaseController {

    @Resource
    private IObsOrderFaultService orderFaultService;

    @Resource
    private IObsOrderInfoService orderInfoService;

    @Resource
    private IObsOrderProcessService processService;

    @Resource
    private IObsLocalPhoneService phoneService;

    @Resource
    private ISysConfigService configService;

    @PostMapping("addOrder")
    @PreAuthorize("@ss.hasPermi('obstacles:server:add')")
    @ApiOperation("创建工单")
    public CommonResult add(@RequestBody OrderAddDto addDto){
        orderFaultService.add(addDto);
        return CommonResult.success();
    }

    @PostMapping("edit")
    @PreAuthorize("@ss.hasPermi('obstacles:server:edit')")
    @ApiOperation("修改工单")
    public CommonResult edit(@RequestBody @Valid OrderEditDto editDto){
        orderFaultService.edit(editDto);
        return CommonResult.success();
    }

    @PostMapping("page")
    @PreAuthorize("@ss.hasPermi('obstacles:server:page')")
    @ApiOperation("服务台分页查询")
    public TableDataInfo<ServerPageVO> page(@RequestBody ServerPageDto pageDto, BasePage page){
        List<ServerPageVO> serverPageVOS = orderFaultService.serverPage(pageDto, page);
        return getDataTable(serverPageVOS);
    }

    @GetMapping("serverUserList")
    @PreAuthorize("@ss.hasPermi('obstacles:server:page')")
    @ApiOperation("服务台人员")
    public CommonResult<List<SimpleUserVo>> serverUser(){
        List<SimpleUserVo> list = orderInfoService.lambdaQuery()
                .select(ObsOrderInfo::getReception)
                .isNotNull(ObsOrderInfo::getReception)
                .groupBy(ObsOrderInfo::getReception).list().stream().map(data->new SimpleUserVo(data.getReception())).collect(Collectors.toList());
        return CommonResult.success(ConversionUtil.conversionList(list,SimpleUserVo.class));
    }

    @PostMapping("callPage")
    @PreAuthorize("@ss.hasPermi('obstacles:server:page')")
    @ApiOperation("服务台电话报修分页查询")
    public TableDataInfo<ServerCallPageVO> callPage(@RequestBody ServerCallPageDto pageDto, BasePage page){
        List<ServerCallPageVO> serverPageVOS = orderFaultService.serverCallPage(pageDto, page);
        return getDataTable(serverPageVOS);
    }

    @GetMapping("linkOrder")
    @PreAuthorize("@ss.hasPermi('obstacles:server:add')")
    @ApiOperation("相关工单")
    public CommonResult<List<LinkOrderVO>> linkOrder(String phone){
        List<LinkOrderVO> list = orderFaultService.linkOrder(phone);
        return CommonResult.success(list);
    }

    @PostMapping("count")
    @PreAuthorize("@ss.hasPermi('obstacles:server:page')")
    @ApiOperation("服务台统计计数")
    public CommonResult<ServerCountVO> count(@RequestBody ServerTotalDto totalDto){
        ServerCountVO countVO = orderFaultService.serverCount(totalDto);
        return CommonResult.success(countVO);
    }

    @GetMapping("detail/{orderNum}")
    @PreAuthorize("@ss.hasPermi('obstacles:server:detail')")
    @ApiOperation("工单详情")
    public CommonResult<OrderDetailVO> detail(@PathVariable("orderNum")String orderNum){
        return CommonResult.success(orderInfoService.detail(orderNum));
    }

    @GetMapping("order/time/{orderNum}")
    @PreAuthorize("@ss.hasPermi('obstacles:server:detail')")
    @ApiOperation("获取处理耗时信息")
    public CommonResult<OrderMakeInfoDto> orderTime(@PathVariable("orderNum")String orderNum){
        return CommonResult.success(orderInfoService.orderTime(orderNum));
    }

    @GetMapping("detail/process/{orderNum}")
    @PreAuthorize("@ss.hasPermi('obstacles:server:process:detail')")
    @ApiOperation("工单流程信息")
    public CommonResult<List<ProcessVO>> list(@PathVariable("orderNum")String orderNum){
        return CommonResult.success(processService.list(orderNum));
    }

    @GetMapping("seat/phone")
    @ApiOperation("服务台注册电话")
    @PreAuthorize("@ss.hasPermi('obstacles:server:process:seat')")
    public CommonResult<List<LocalPhoneVO>> seatPhone(){
        return CommonResult.success(phoneService.list().stream().map(LocalPhoneVO::new).collect(Collectors.toList()));
    }

    @PutMapping("deal/invalid")
    @ApiOperation("无效电话")
    @PreAuthorize("@ss.hasPermi('obstacles:server:deal:invalid')")
    public CommonResult dealInvalid(@RequestBody SimpleDto<Long> dto){
        orderInfoService.dealInvalid(dto.getData());
        return CommonResult.success();
    }

    @PutMapping("allocate")
    @ApiOperation("派单")
    public CommonResult allocate(@RequestBody AllocateDto dto){
        orderFaultService.allocate(dto);
        return CommonResult.success();
    }

    @PutMapping("deal/find")
    @ApiOperation("电话找人")
    @PreAuthorize("@ss.hasPermi('obstacles:server:deal:find')")
    public CommonResult dealFind(@RequestBody FindUserDto dto){
        orderInfoService.dealFind(dto);
        return CommonResult.success();
    }

    @PutMapping("link")
    @ApiOperation("关联工单")
    @PreAuthorize("@ss.hasPermi('obstacles:server:link')")
    public CommonResult link(@RequestBody OrderLinkedDto dto){
        orderInfoService.link(dto);
        return CommonResult.success();
    }

    @GetMapping("print")
    @ApiOperation(value = "打印工单",produces = MediaType.IMAGE_JPEG_VALUE)
    @PreAuthorize("@ss.hasPermi('obstacles:server:print')")
    public void print(Long id,HttpServletResponse response){
        OrderPrintVO orderExportDto = orderFaultService.getPrintOrderInfo(id);
        if (ObjectUtil.isNull(orderExportDto)) {
            throw new ServiceException("工单不存在");
        }
        String cachePath = configService.selectConfigByKey(ConfigKeyConstant.CACHE_FILE_CONFIG);
        String path = WordUtil.getUploadPath(cachePath);
        Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(orderExportDto)).toJavaObject(Map.class);
        File file = WordUtil.exportMillCertificateWord(map, path, "print.ftl");
        WordUtil.wordToImage(file, path + File.separator + "orderInfo.jpg");
        File image = new File(path + File.separator + "orderInfo.jpg");
        DownloadUtil.download(image,response);
    }

}
